﻿//-----------------------------------------------------------------------
// <copyright file="PackageModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.Package
{
    using System;
    using System.IO;
    using App.Exceptions;
    using Newtonsoft.Json;
    using TileTool.Log;
    using TileTool.Threading.Future.Generic;

    /// <summary>
    /// Application package module.
    /// </summary>
    public class PackageModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "PackageModule";

        /// <summary>
        /// Default package file name to use.
        /// </summary>
        private const string PackageFileName = @"Packages/base.package.tiletool";

        #endregion

        #region Fields - Private

        /// <summary>
        /// Package data we should use.
        /// </summary>
        private PackageData data = null;

        #endregion

        #region Properties - Public

        /// <summary>
        /// Gets the package data we should be using.
        /// </summary>
        public PackageData Data
        {
            get
            {
                return this.data;
            }
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            this.DeserializeActivePackage();

            base.Startup();
        }

        /// <summary>
        /// Called when the application is shutting down.
        /// </summary>
        public override void Shutdown()
        {
            base.Shutdown();
        }

        /// <summary>
        /// Get a components name from its alias in the package.
        /// </summary>
        /// <param name="alias">Component alias we are finding a component name for.</param>
        /// <returns>Returns the component name associated with the alias or an empty string if there is none.</returns>
        public string GetComponentName(string alias)
        {
            if (string.IsNullOrEmpty(alias))
            {
                return string.Empty;
            }

            if (this.data.Components == null)
            {
                return string.Empty;
            }
            
            string componentName = string.Empty;

            if (!this.data.Components.TryGetValue(alias, out componentName))
            {
                return string.Empty;
            }

            return componentName;
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Deserialize the currently active package data.
        /// </summary>
        private void DeserializeActivePackage()
        {
            try
            {
                using (FileStream fileStream = new FileStream(PackageFileName, FileMode.Open))
                {
                    using (StreamReader streamReader = new StreamReader(fileStream))
                    {
                        JsonSerializerSettings settings = new JsonSerializerSettings();

                        settings.NullValueHandling = NullValueHandling.Ignore;
                        settings.ObjectCreationHandling = ObjectCreationHandling.Auto;
                        settings.TypeNameHandling = TypeNameHandling.None;

                        using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                        {
                            JsonSerializer serializer = JsonSerializer.Create(settings);

                            this.data = serializer.Deserialize<PackageData>(jsonReader);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogSystem.LogError(LogGroup, "Failed to load package data: " + e.Message);
                throw new AppException("Failed to load package data: " + e.Message, e);
            }
        }

        #endregion
    }
}
